package com.bawei.module_goods.ui

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_goods.R
import com.bawei.module_goods.adapter.OptionAdapter
import com.bawei.module_goods.databinding.DialogSkuSelectBinding
import com.bawei.module_goods.entity.Sku
import com.bawei.module_goods.repository.ShoppingCartRepository
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.launch

class SkuSelectDialog(
    private val skuList: List<Sku>,
    private val mainImgUrl: String?,
    private val price: Int?,
    private val code: String?,
    private val onSelected: ((model: String?, quantity: Int) -> Unit)? = null
) : BottomSheetDialogFragment() {

    private var _binding: DialogSkuSelectBinding? = null
    private val binding get() = _binding!!

    private var selectedModel: String? = null
    private var selectedSku: Sku? = null
    private var quantity: Int = 1
    private var maxStock: Int = 1

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DialogSkuSelectBinding.inflate(inflater, container, false)
        return binding.root
    }

    private fun parseAttrs(attrs: String?): Map<String, String> {
        if (attrs.isNullOrBlank()) return emptyMap()
        return try {
            if (attrs.trim().startsWith("{")) {
                Gson().fromJson(attrs, object : TypeToken<Map<String, String>>() {}.type)
            } else {
                attrs.split(",", "，").mapNotNull {
                    val arr = it.split(":", "：")
                    if (arr.size == 2) arr[0].trim() to arr[1].trim() else null
                }.toMap()
            }
        } catch (e: Exception) {
            emptyMap()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // 商品图片、价格、编号
        Glide.with(this).load(mainImgUrl).into(binding.ivGoods)
        binding.tvPrice.text = "¥${price ?: "--"}"
        binding.tvCode.text = "编号：${code ?: "--"}"
        binding.ivGoods.setOnClickListener {
            val imgUrl = selectedSku?.skuImgUrl ?: mainImgUrl
        }

        // 型号（skuName）选项
        val models = skuList.mapNotNull { it.skuName }.filter { it.isNotBlank() }.distinct()
        if (models.isNotEmpty()) {
            val modelAdapter = OptionAdapter(models, models.first()) { selected ->
                selectedModel = selected
                selectedSku = skuList.find { it.skuName == selected }
                // 更新顶部信息
                Glide.with(this).load(selectedSku?.skuImgUrl).into(binding.ivGoods)
                binding.tvPrice.text = "¥${selectedSku?.purchasePrice ?: "--"}"
                binding.tvCode.text = "编号：${selectedSku?.skuCode ?: "--"}"
                // 更新库存
                maxStock = selectedSku?.stocks ?: 1
                // 如果当前数量大于库存，自动调整
                if (quantity > maxStock) {
                    quantity = maxStock
                    binding.tvQuantity.text = quantity.toString()
                }
            }
            binding.rvModel.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            binding.rvModel.adapter = modelAdapter
            if (binding.rvModel.itemDecorationCount == 0) {
                binding.rvModel.addItemDecoration(SpaceItemDecoration(24))
            }
            selectedModel = models.first()
            selectedSku = skuList.find { it.skuName == selectedModel }
            Glide.with(this).load(selectedSku?.skuImgUrl).into(binding.ivGoods)
            binding.tvPrice.text = "¥${selectedSku?.purchasePrice ?: "--"}"
            binding.tvCode.text = "编号：${selectedSku?.skuCode ?: "--"}"
            maxStock = selectedSku?.stocks ?: 1
            binding.rvModel.visibility = View.VISIBLE
        } else {
            binding.rvModel.visibility = View.GONE
        }

        // 数量选择
        binding.btnMinus.setOnClickListener {
            if (quantity > 1) {
                quantity--
                binding.tvQuantity.text = quantity.toString()
            }
        }
        binding.btnPlus.setOnClickListener {
            if (quantity < maxStock) {
                quantity++
                binding.tvQuantity.text = quantity.toString()
            } else {
                ToastUtils.showShort("不能超过库存数量")
            }
        }
        // 底部按钮
        binding.btnAddCart.setOnClickListener {
            val sku = selectedSku
            if (sku == null) {
                ToastUtils.showShort("请选择型号")
                return@setOnClickListener
            }
            lifecycleScope.launch {
                val repo = ShoppingCartRepository()
                val result = repo.addToCart(
                    goodsId = sku.goodsId ?: 0,
                    skuId = sku.id ?: 0,
                    skuCode = sku.skuCode ?: "",
                    skuName = sku.skuName ?: "",
                    number = quantity
                )
                if (result.isNotBlank()) {
                    ToastUtils.showShort("添加成功")
                } else {
                    ToastUtils.showShort("添加失败")
                }
                dismiss()
            }
        }
        binding.btnBuy.setOnClickListener {
            val sku = selectedSku
            if (sku == null) {
                ToastUtils.showShort("请选择型号")
                return@setOnClickListener
            }
            onSelected?.invoke(selectedModel, quantity)
            dismiss()
        }
        binding.ivClose.setOnClickListener {
            //关闭弹窗
            dismiss()
        }
        // 让型号RecyclerView支持嵌套滑动，避免与BottomSheet滑动冲突
        binding.rvModel.isNestedScrollingEnabled = true
    }

    override fun onStart() {
        super.onStart()
        binding.rvModel.isNestedScrollingEnabled = true
    }

    private fun createOptionButton(text: String): TextView {
        val btn = TextView(requireContext())
        btn.text = text
        btn.setPadding(24, 12, 24, 12)
        btn.setBackgroundResource(R.drawable.bg_option_unselected)
        btn.setTextColor(resources.getColor(R.color.black))
        btn.textSize = 16f
        btn.isClickable = true
        btn.isFocusable = true
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.setMargins(12, 0, 12, 0)
        btn.layoutParams = params
        return btn
    }

    private fun updateOptionSelection(group: LinearLayout, selected: String) {
        for (i in 0 until group.childCount) {
            val child = group.getChildAt(i) as TextView
            if (child.text == selected) {
                child.setBackgroundResource(R.drawable.bg_option_selected)
            } else {
                child.setBackgroundResource(R.drawable.bg_option_unselected)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

class SpaceItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        outRect.right = space
    }
} 